import {
  Button,
  Form,
  Input,
  Select,
  Upload,
  message,
  AutoComplete,
  Tabs,
  Row,
  Col,
  Spin,
} from 'antd';
// eslint-disable-next-line import/no-extraneous-dependencies
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PropTypes from 'prop-types';
import styles from './BaseView.less';
import { getWebPath } from '../../../utils/request';
import uiUtils, { rulesReg, rulesRemote } from '../../../utils/uiUtils';

const FormItem = Form.Item;
const TextArea = Input.TextArea;
const { Option } = Select; // 头像组件 方便以后独立，增加裁剪之类的功能

@connect(({ accountAndsettings }) => ({
  currentUser: '',
}))
class BaseView extends Component {
  view = undefined;

  mailSuffix = ['163.com', '126.com', 'gmail.com', 'qq.com', 'hotmail.com', 'sohu.com', 'sina.com'];

  constructor(props) {
    super(props);
    this.state = {
      user: [],
      mailDataSource: [],
      headImg: undefined,
      loading: true,
    };
    this.getBaseInfo();
  }

  componentDidMount() {}

  getBaseInfo = () => {
    requestPromise(`${getWebPath('sys/user/info')}`, {
      method: 'GET',
    }).then(res => {
      this.setState({
        user: res.user,
        headImg: res.user.headImg,
        loading: false,
      });
    });
  };

  updatePerson = () => {
    const user = Object.assign(this.state.user, this.props.form.getFieldsValue());
    user.headImg = this.state.headImg;
    this.props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-prototype-builtins
      if (!err) {
        this.setState({ updatePersonLoading: true });
        const url = '/sys/user/update';
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: user,
        }).then(res => {
          this.setState({
            updatePersonLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            const { dispatch } = this.props;
            dispatch({
              type: 'user/fetchCurrent',
            });
          }
        });
      }
    });
  };

  getPropsByKey = prop => {
    const model = this.state.user || {};
    return model[prop];
  };

  autoCompleteHandleSearch = value => {
    this.setState({
      mailDataSource:
        !value || value.indexOf('@') === -1
          ? []
          : this.mailSuffix
              .map(en => `${value.split('@', 2)[0]}@${en}`)
              .filter(en => en.indexOf(value.split('@', 2)[1]) !== -1),
    });
  };

  handleUploadImgOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            this.setState({
              headImg: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  render() {
    const {
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const model = this.state.user;
    const inputUsernameRules = [
      {
        required: true,
        message: '登录名必填',
      },
      {
        min: 3,
        max: 50,
        message: '长度不在范围内',
      },
      rulesReg('username'),
      rulesRemote('POST', getWebPath('/sys/user/checkUsernameExist'), {
        usernameOldValue: this.getPropsByKey('username'),
        userinfoIsAdd: false,
      }),
    ];
    const inputMobileRules = [
      {
        min: 11,
        max: 11,
        message: '手机号必须是11个字符',
      },
      rulesReg('mobile'),
      rulesRemote('POST', getWebPath('/sys/user/checkMobileExist'), {
        mobileOldValue: this.getPropsByKey('mobile'),
        userinfoIsAdd: false,
      }),
    ];
    const inputEmailRules = [
      {
        min: 5,
        max: 50,
        message: '长度不在范围内',
      },
      rulesReg('email'),
      rulesRemote('POST', getWebPath('/sys/user/checkEamilExist'), {
        emailOldValue: this.getPropsByKey('email'),
        userinfoIsAdd: false,
      }),
    ];
    const headImgProps = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'sys_user', isImage: false, acceptFileExts: 'all' },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadImgOnChange,
      multiple: false,
      accept:
        '.jpg, .jpeg, .png, .bmp, ' + //image/*
        '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,' + //excel
        '.doc,.docx,,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, ' + //word
        '.pdf, .txt, .xml',
    };
    const AvatarView = () => (
      <Fragment>
        <div className={styles.avatar_title}>
          <FormattedMessage id="accountandsettings.basic.avatar" defaultMessage="头像" />
        </div>
        {this.state.headImg !== undefined && (
          <div className={styles.avatar}>
            <img src={this.state.headImg} alt="avatar" />
          </div>
        )}

        <Upload {...headImgProps}>
          <div className={styles.button_view}>
            <Button icon="upload">
              <FormattedMessage
                id="accountandsettings.basic.change-avatar"
                defaultMessage="上传头像"
              />
            </Button>
          </div>
        </Upload>
      </Fragment>
    );

    return (
      <Spin spinning={this.state.loading}>
        <Tabs style={{ marginTop: '20px' }} defaultActiveKey="0" type="line">
          <Tabs.TabPane tab="个人信息" key="0">
            <div className={styles.baseView}>
              <div className={styles.left}>
                <Form layout="vertical">
                  <FormItem label="登录名">
                    {getFieldDecorator('username', {
                      initialValue: model.username,
                      rules: inputUsernameRules,
                    })(<Input type="text" disabled maxLength={50} placeholder="登录名" />)}
                  </FormItem>
                  <FormItem label="邮箱">
                    {getFieldDecorator('email', {
                      initialValue: model.email,
                      rules: inputEmailRules,
                    })(
                      <AutoComplete
                        placeholder="邮箱"
                        style={{ width: '100%' }}
                        dataSource={this.state.mailDataSource}
                        onSearch={this.autoCompleteHandleSearch}
                      />
                    )}
                  </FormItem>
                  <FormItem label="备注">
                    {getFieldDecorator('remarks', {
                      initialValue: model.remarks,
                      rules: [
                        {
                          min: 0,
                          max: 100,
                          message: '最长100个字符',
                        },
                      ],
                    })(<TextArea rows={3} maxLength={100} placeholder="备注" />)}
                  </FormItem>
                  <Button
                    type="primary"
                    loading={this.state.updatePersonLoading}
                    onClick={() => {
                      this.updatePerson();
                    }}
                  >
                    <FormattedMessage id="accountandsettings.basic.update" defaultMessage="更新" />
                  </Button>
                </Form>
              </div>
              <div className={styles.right}>
                <Form layout="vertical">
                  <FormItem label="真实姓名">
                    {getFieldDecorator('nickName', {
                      initialValue: model.nickName,
                    })(<Input type="text" maxLength={50} placeholder="真实姓名" />)}
                  </FormItem>
                  <FormItem label="手机号">
                    {getFieldDecorator('mobile', {
                      initialValue: model.mobile,
                      rules: inputMobileRules,
                    })(
                      <Input type="text" maxLength={11} autocomplete="off" placeholder="手机号" />
                    )}
                  </FormItem>
                  <FormItem label="注册时间">{model.createTime}</FormItem>
                </Form>
              </div>
              <div className={styles.right}>
                <AvatarView />
              </div>
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane tab="修改密码" key="1">
            <UpdatePassrowdForm
              model={model}
              wrappedComponentRef={inst => {
                this.updatePassrowdForm = inst;
              }}
            />
          </Tabs.TabPane>
        </Tabs>
      </Spin>
    );
  }
}

export default Form.create()(BaseView);

/**
 *  修改密码Form
 */

/* eslint react/no-multi-comp:0 */
class UpdatePassrowdForm extends React.Component {
  static propTypes = {
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    model: null,
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  //判断两次密码是否一致
  checkConfirm = (rule, value, callback) => {
    const newPassword = this.props.form.getFieldValue('newPassword');
    const repeatPassword = this.props.form.getFieldValue('repeatPassword');
    if (newPassword.trim() !== '' && repeatPassword.trim() !== '') {
      if (newPassword !== repeatPassword) {
        return callback('两次密码不一致!');
      }
    }
    return callback();
  };

  updatePassrod = () => {
    const user = {
      password: this.props.form.getFieldValue('nowPassword'),
      newPassword: this.props.form.getFieldValue('newPassword'),
    };
    this.props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-prototype-builtins
      if (!err) {
        if (user.password === user.newPassword) {
          uiUtils.showMessage(`新密码与当前密码一样，不用修改！`, 'error');
          return;
        }
        this.setState({ updatePasswordLoading: true });
        const url = '/sys/user/password';
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: user,
          contentType: 'application/x-www-form-urlencoded',
        }).then(res => {
          this.setState({
            updatePasswordLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
          }
        });
      }
    });
  };

  render() {
    const model = this.props.model || {};
    const { getFieldDecorator } = this.props.form;
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <div className={styles.baseView}>
        <div className={styles.left}>
          <Form layout="vertical">
            <FormItem label="当前密码">
              {getFieldDecorator('nowPassword', {
                rules: [
                  {
                    required: true,
                    message: '必填',
                  },
                  {
                    min: 6,
                    message: '密码最少6位',
                  },
                ],
              })(<Input.Password type="text" maxLength={50} placeholder="当前密码" />)}
            </FormItem>
            <FormItem label="新密码">
              {getFieldDecorator('newPassword', {
                rules: [
                  {
                    required: true,
                    message: '必填',
                  },
                  {
                    min: 6,
                    message: '密码最少6位',
                  },
                  { validator: this.checkConfirm },
                ],
                validateTrigger: 'onBlur',
              })(<Input.Password type="text" maxLength={50} placeholder="新密码" />)}
            </FormItem>
            <FormItem label="再次输入密码">
              {getFieldDecorator('repeatPassword', {
                rules: [
                  {
                    required: true,
                    message: '必填',
                  },
                  {
                    min: 6,
                    message: '密码最少6位',
                  },
                  { validator: this.checkConfirm },
                ],
                validateTrigger: 'onBlur',
              })(<Input.Password type="text" maxLength={50} placeholder="再次输入密码" />)}
            </FormItem>
            <Button
              type="primary"
              loading={this.state.updatePasswordLoading}
              onClick={() => {
                this.updatePassrod();
              }}
            >
              <FormattedMessage id="accountandsettings.basic.update" defaultMessage="更新" />
            </Button>
          </Form>
        </div>
      </div>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
UpdatePassrowdForm = Form.create({})(UpdatePassrowdForm);
